package lab03;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;

public class Test06 {
    public static void main(String[] args) {
         String path = "G:\\words.txt";
        //map(key,value)
        //key  value
        //hell0  1

        Set<String>set = new HashSet<>();//set数组有去重的功能
        List<String>list = new ArrayList<>() ;//用来计算有多少个单词

        Map<String,Integer> map = new HashMap<>();
        try {
            RandomAccessFile file = new RandomAccessFile(path,"rw");
            String line = null;
            int i = 0;
           while( (line = file.readLine()) != null){
               System.out.println(line);
               i = i+1;
              String [] st = line.split(" ");//将一行单词转化为字符串数组，以空格分隔

               for (int j = 0;j< st.length;j++){
                   set.add(st[j]);
                   list.add(st[j]);
               }
               //先判断这个map里面有没有这个key,没有就直接将value赋值
           }//读一行
               System.out.println("一共出现了"+ i +"个单词");
               System.out.println("有"+set.size()+"个不同的单词");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //排序跟求频率太难了，还没有看懂
        //frequency(Collection<?>, Object) 方法用于获取所指定元素集合等于指定对象中的数量。
        /*public class CollectionsDemo {
   public static void main(String args[]) {
      // create array list object
      List arrlist = new ArrayList();

      // populate the list
      arrlist.add("A");
      arrlist.add("B");
      arrlist.add("C");
      arrlist.add("C");
      arrlist.add("C");

      // check frequensy of 'C'
      int freq = Collections.frequency(arrlist, "C");

      System.out.println("Frequency of 'C' is: "+freq);
   }
}
        * */
        for (int i = 0; i < list.size(); i++) {
            map.put(list.get(i), Collections.frequency(list, list.get(i)));
        }

        List<Map.Entry<String, Integer>> mapSort = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());  //此段代码是对map集合按value值进行排序，
/*Collections是一个工具类，sort是其中的静态方法，是用来对List类型进行排序的，它有两种参数形式
public static <T extends Comparable<? super T>> void sort(List<T> list) {
        list.sort(null);
    }

    public static <T> void sort(List<T> list, Comparator<? super T> c) {
        list.sort(c);
    }
* */
        Collections.sort(mapSort, new Comparator<Map.Entry<String, Integer>>() {                                  //代码较难，现在还无法理解.
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return (o2.getValue() - o1.getValue());
            }
        });

        for (int i = 0; i < mapSort.size(); i++) {
            String id = mapSort.get(i).toString();
            System.out.println(id);
        }
    }
    }

